package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log4j2
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 存储喜欢数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null || dto.getEquipmentId() == null
                || (dto.getType() < 0 && dto.getType() > 2) || (dto.getOperation() < 0 && dto.getOperation() > 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = null;
        if (apUser == null) {
            //检查实体
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        } else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        }
        //点赞或取消赞
        //查看是否已经点赞
        ApLikesBehavior apLikesBehavior1 = getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (apLikesBehavior1 == null && dto.getOperation() == 0) {

            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();

            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setType(dto.getType());
            save(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            //取消赞
            apLikesBehavior1.setOperation(dto.getOperation());
            updateById(apLikesBehavior1);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
